<template>
  <view class="user-warp">
		<uni-easyinput class="uni-mt-5" suffixIcon="search" readonly disabled :value="selectLabel.join()" placeholder="请选择" @iconClick="iconClick"></uni-easyinput>
    <uni-popup ref="popup">
			<view style="height: 60vh;background-color: #fff;">
				<view class="pop-header">
					<span class="pop-header-left" @click="onCancel">取消</span>
					<span class="pop-header-title">{{placeholder}}</span>
					<span class="pop-header-right" @click="onConfirm" :style="{color}" >确认</span>
				</view>
				<view style="background-color: #fff;padding: 15rpx 25rpx;">
					<view style="display: flex;justify-content: center;line-height: 65rpx;height: 65rpx;">
						<view v-show="!showSelectRows && selectRowsMap.size > 0" style="width: 90px;" @click="handleSelectRows">
							已选择  {{ selectRowsMap.size }} 
						</view>
						<view v-show="showSelectRows" style="width: 90px;" @click="handleSelectRows">
							返回
						</view>
						<!-- <uni-easyinput class="uni-mt-5" suffixIcon="search" v-model="queryParam[optionKey.label]" placeholder="请输入" @iconClick="onSearch"></uni-easyinput> -->
						<view style="display: flex;justify-content: center;flex: 1;background-color: #f5f5f5;border-radius: 10rpx;padding: 0 25rpx;">
							<input style="line-height: 65rpx;height: 65rpx;flex: 1;" placeholder="请输入" v-model="queryParam[optionKey.label]" />
							<view @click="onSearch" style="width: 80rpx;text-align: center;margin-left: 25rpx;" :style="{color}">
								搜索
							</view>
						</view>
					</view>
				</view>
				<scroll-view
					:scroll-y="true"
					:upper-threshold="50"
					style="height:50vh;padding: 10px;"
				>
					<view v-show="!showSelectRows" style="height:calc(60vh - 260rpx)">
						<uni-data-checkbox mode="list" icon="right" :value="selectValue" :multiple="multiple" :localdata="dataSource" @change="change"></uni-data-checkbox>
						<uni-pagination showIcon :current="ipagination.currentPage" :total="ipagination.total" @change="handlePage"></uni-pagination>
					</view>
					<view v-show="showSelectRows">
						<uni-data-checkbox mode="list" icon="right" v-model="selectValue" @change="changeSelectRow" :multiple="true" :localdata="selectRows"></uni-data-checkbox>
					</view>
				</scroll-view>
			</view>
    </uni-popup>
  </view>
</template>

<script>
import listMixins from '@/mixins/listMixins'
import { getAction } from '@/api/manage'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/utils/constant'
export default {
	mixins:[listMixins],
	props:{
		color: {
			type: String,
			default: '#0081ff'
		},
		value: {
			type: String,
			default: ''
		},
		multiple:{
			type:Boolean,
			default:false
		},
		placeholder:{
			type:String,
			default:'请选择'
		},
		disabled:Boolean,
		url: {
			type:String,
			require:true
		},
		optionKey: {
			type: Object,
			default: () => ({ label: 'label', value: 'value' })
		},
	},
  data() {
    return {
			selectLabel:[],
			selectValue:[],
			selectRowsMap:new Map(),
			selectRows:[],
			ipagination:{
				total: 0,
				currentPage: 1,
				pageSize: 10
			},
			showSelectRows:false,
			dataSource:[]
    }
  },
	watch:{
		value:{
			handler(newVal){
				if(newVal !== this.selectValue.join()){
					this.getSelectRows(newVal)
				}
			},
			immediate:true,
			deep:true
		}
	},
  methods: {
		async loadData() {//请求用户列表数据
			if (!this.url) {
				return
			}
			let params = this.getQueryParams() // 查询条件
			this.loading = true
			this.loadMoreLoading = 'loading'
			let res = await getAction(this.url, params)
			const data = res.data
			if(data.success && data.result.content.length>0){
				this.ipagination.total = data.result.totalElements
				this.dataSource = this.creatdSelectOption(data.result.content)
			}
		},
		handlePage({ current }){
			this.ipagination.currentPage = current
			this.loadData()
		},
		async getSelectRows(selectValue){//根据用户名请求用户列表数据
			const queryParam = new Criteria()
			queryParam.addCriterions({
				[this.optionKey.value]:selectValue
			}, OPERATOR.IN) // 过滤参数转换为jpa支持格式
			var param = Object.assign({}, {
				criteria: queryParam.getEncode()
			})
			param.pageNo = 1
			param.pageSize = 999
			const res = await getAction(this.url, param)
			const data = res.data
			if(data.success){
				this.setSelectRows(data.result.content)
				this.setSelectLabel()
			}
		},
    iconClick() {//显示popup
			if(!this.disabled){
				this.getSelectRows(this.value)
				this.$refs.popup.open('bottom')
			}
    },
		change(e) {//选择
			const values = e.detail.value
			if(this.multiple){		
				this.dataSource.forEach(item => {
					if(values.includes(item.value)){ // 选择的插入到map中
						this.selectRowsMap.set(item.value,item)
					}else if(this.selectRowsMap.has(item.value)){ // 在map中移除取消选中的
						this.selectRowsMap.delete(item.value)
					}
				})
				this.selectValue = Array.from(this.selectRowsMap.keys())
			}else{
				const data = e.detail.data
				this.selectRowsMap = new Map()
				this.selectRowsMap.set(values,data)
				this.selectValue = values
			}
		},
		onCancel() { //点击取消
			this.$refs.popup.close()
			this.$emit('cancel')
		},
		onConfirm(){//点击确认
			this.$refs.popup.close()
			this.setSelectLabel()
			const selectRows = Array.from(this.selectRowsMap.values()).map(item => {
				return item.data
			})
			this.$emit('change',this.selectValue.join(),selectRows)
		},
		setSelectRows(list){//设置已选择用户信息
			const selectUser = this.creatdSelectOption(list)
			this.selectRowsMap = new Map()
			selectUser.forEach(item => {
				this.selectRowsMap.set(item.value,item)
			})
			this.selectValue = Array.from(this.selectRowsMap.keys())
		},
		setSelectLabel(){//设置输入框显示的用户名称
			this.selectLabel = []
			Array.from(this.selectRowsMap.values()).forEach(item => {
				this.selectLabel.push(item.text)
			})
		},
		creatdSelectOption(list){//构造Option
			const options = []
			list.forEach(item => {
				options.push({
					text: item[this.optionKey.label],
					value:item[this.optionKey.value],
					data:{...item}
				})
			})
			return options
		},
		handleSelectRows(){
			this.showSelectRows = !this.showSelectRows
			if(this.showSelectRows){
				this.selectRows = Array.from(this.selectRowsMap.values())
			}
			// else{
			// 	Array.from(this.selectRowsMap.keys()).forEach(key => {
			// 		if(!this.selectValue.includes(key)){
			// 			this.selectRowsMap.delete(key)
			// 		}
			// 	})
			// }
		},
		changeSelectRow(e){
			const datas = e.detail.data
			this.selectRowsMap = new Map()
			datas.forEach(item => {
				this.selectRowsMap.set(item.value,item)
			})
		}
  },
	model: {
		prop: 'value',
		event: 'change'
	}
};
</script>

<style lang="scss">
	.uni-list{
		width: 100%;
	}
	.uni-list-item {
		border-bottom-style: solid;
		border-bottom-width: 1px;
		border-bottom-color: #eee;
		font-size: 14px;
	}

	.uni-list-item__container {
		/* #ifndef APP-NVUE */
		display: flex;
		width: 100%;
		box-sizing: border-box;
		/* #endif */
		padding: 12px 15px;
		flex: 1;
		position: relative;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.uni-list-item__content-title {
		font-size: 14px;
		color: #666;
	}
	.popup-content {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		// top: 0;
		background-color: #ffffff;
	}
	.pop {
		&-header {
			height: 44px;
			border-bottom: 1px solid #ebedf0;
			background-color: #f7f8fa;
			align-items: center;
			display: flex;
			justify-content: center;
			font-size: 26rpx;
	
			&-left {
				width: 44px;
				text-align: center;
				color: #666;
			}
	
			&-right {
				width: 44px;
				text-align: center;
			}
	
			&-title {
				flex: 4;
				text-align: center;
				color: 32rpx;
				padding: 0 5px;
			}
		}
	
		&-main {
			overflow-x: hidden;
			overflow-y: auto;
			-webkit-overflow-scrolling: touch;
			scroll-behavior: smooth;
			height: 40vh;
		}
	}
	.user-warp{
		width: 100%;
	}
</style>